const jwt = require("jsonwebtoken")
const { tokenSecret } = require('../config')

const createToken = (info, expiresIn = 60 * 60 * 24 * 1000) => {
    return jwt.sign(info, tokenSecret, {
        expiresIn
    })
}

const verifyToken = (token) => new Promise((resolve, reject) => {
    try{
        jwt.verify(token, tokenSecret, (err, decoded)=>{
            if(err){
                if (err.name === 'TokenExpiredError') {
                    return reject('token expired' )
                }
                return reject('token invalid')
            }
            resolve(decoded)
        })
    }catch (e) {
        reject(e)
    }
})

module.exports = {
    createToken, verifyToken
}
